package quicksort;

import common.CreateTestArrUtils;

import java.util.Arrays;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/8/13 4:39
 * 快速排序(挖坑法)
 * 时间复杂度 O(nlog n)
 */
public class QuickSort01 {

    // 快排
    public static void quickSort(int[] arr) {
        quick(arr, 0, arr.length - 1);
    }

    private static void quick(int[] arr, int start, int end) {
        if (start >= end) {
            return;
        }
        int pivot = partition(arr, start, end); // 划分
        quick(arr, start, pivot - 1);
        quick(arr, pivot + 1, end);
    }

    private static int partition(int[] arr, int left, int right) {
        int temp = arr[left];
        while (left < right) {
            while (left < right && arr[right] >= temp) {
                right--;
            }
            arr[left] = arr[right];
            while (left < right && arr[left] <= temp) {
                left++;
            }
            arr[right] = arr[left];
        }
        arr[left] = temp;
        return left;
    }

    // 测试
    public static void main(String[] args) {
        int[] descArr = CreateTestArrUtils.createDescArr(100);
        System.out.println("原数组 arr=" + Arrays.toString(descArr));
        quickSort(descArr);
        System.out.println("排序后数组 arr=" + Arrays.toString(descArr));
    }
}
